import logging
import requests
import re
import uuid

logger = logging.getLogger(__name__)


class ColumnPredictor:

    def __init__(self):
        self.token_url = "http://10.62.170.202:54246/get_token"

    def get_token(self):
        log_response = requests.get(self.token_url)
        res = log_response.json()
        token = res['token']
        return token

    @staticmethod
    def extract_column_name(data):
        """
        从DeepSeek R1模型的响应文件中提取最大电压信号列名
        """
        try:
            # 获取响应消息内容
            msg_content = data.get('msg', '')

            # 使用正则表达式提取最终列名（位于</think>标签之后）
            match = re.search(r'</think>\s*(\S+)', msg_content)
            if match:
                return match.group(1)

            # 如果正则匹配失败，尝试直接提取最后一部分非空内容
            parts = msg_content.split()
            if parts:
                return parts[-1]
        except:
            print("模型响应解析失败")
        return ""

    def find_column(self, token, target, columns):
        url = "https://ai.fdbatt.com/prod-ui/chat/sendMsg"
        headers = {
            "Authorization": f"Bearer {token}"
        }
        msg = f"从下面这些列名中找出最可能代表\"{target}\"的列名（只输出列名，不要解释）：{",".join(columns)}"
        body = {
            "modelId": "deepseek-r1-chat",
            "msg": msg,
            "sessionId": uuid.uuid4()
        }
        res = requests.post(url=url, headers=headers, data=body)
        target_column = None
        if res['code'] == 200:
            target_column = self.extract_column_name(res.json())
        if target_column in columns:
            return target_column
